package prefetch

import (
	"time"
)

type Engine struct {
	cfg       Config
	monitor   *Monitor
	predictor *Predictor
	scheduler *Scheduler
	store     *Store
}

func NewEngine(cfg Config) *Engine {
	e := &Engine{
		cfg:       cfg,
		monitor:   NewMonitor(),
		predictor: NewPredictor(),
		scheduler: NewScheduler(cfg.DaemonURL),
		store:     NewStore(cfg.StorePath),
	}
	_ = e.store.Load()
	return e
}

func (e *Engine) Run() {
	go e.eventLoop()
	go e.trainLoop()
	select {} // 阻塞主协程
}

func (e *Engine) eventLoop() {
	for ev := range e.monitor.Events() {
		e.predictor.Learn(ev.Path)
	}
}

func (e *Engine) trainLoop() {
	for {
		time.Sleep(10 * time.Second)
		hot := e.predictor.Predict(5)
		e.scheduler.Prefetch(hot)
		e.store.Save()
	}
}
